<template>
  <div class="agency-wrapper">
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="100" class="mb-2">
        <el-col :span="8">
          <el-input placeholder="请输入代理账号" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="search">查询</el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加总代理</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table
        :data="users"
        border
        stripe
        class="mb-2"
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column label="用户名" prop="name" min-width="90"></el-table-column>
        <el-table-column label="姓名" prop="full_name" min-width="90"></el-table-column>
        <el-table-column label="邮箱" prop="email" min-width="110"></el-table-column>
        <!-- <el-table-column label="网站名称" prop="website_name" width="90"></el-table-column>
        <el-table-column label="网站域名" prop="domain_name" width="90"></el-table-column>
        <el-table-column label="网站ip" prop="ip" width="90"></el-table-column>
        <el-table-column label="网站logo" prop="logo" width="90"></el-table-column> -->
        <el-table-column label="开始时间" prop="start_time" width="100"></el-table-column>
        <el-table-column label="结束时间" prop="end_time" width="100"></el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.status == 0 ? '正常' : '禁用'" placement="top">
              <el-switch
                active-value="正常"
                inactive-value="禁用"
                :value="scope.row.status == 0 ? '正常' : '禁用'"
                @change="userStateChanged(scope.row)"
              ></el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row)">编辑</el-button>
            <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetPwd(scope.row)">重置密码</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <Pagination :obj="obj" @pagination="getUserList($event)" />
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px" class="addForm w80">
        <el-form-item label="用户名" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="所占分成比" prop="commission">
          <el-input-number v-model="addForm.commission" :min="0.1" :max="0.9" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="姓名" prop="full_name">
          <el-input v-model="addForm.full_name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="网站名称" prop="website_name">
          <el-input v-model="addForm.website_name"></el-input>
        </el-form-item>
        <el-form-item label="网站域名" prop="domain_name">
          <el-input v-model="addForm.domain_name"></el-input>
        </el-form-item>
        <el-form-item label="网站ip" prop="ip">
          <el-input v-model="addForm.ip"></el-input>
        </el-form-item>
        <el-form-item label="网站logo" prop="logo" :class="{ showLogo: showLogo }">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :class="{ hide: hideUpload }"
            action="http://dev-mall-admin.siyuyunai.com/files/upload"
            list-type="picture-card"
            :file-list="addForm.logoList"
            :data="uploadData"
            :headers="getAuthHeaders()"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="代理时间" required>
          <el-col :span="11">
            <el-form-item prop="start_time">
              <el-date-picker
                type="date"
                placeholder="选择开始时间"
                v-model="addForm.start_time"
                value-format="yyyy-MM-dd"
                @change="dateChange"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="end_time"
              ><el-date-picker
                type="date"
                placeholder="选择结束时间"
                v-model="addForm.end_time"
                value-format="yyyy-MM-dd"
                @change="dateChange"
                style="width: 100%;"
              ></el-date-picker
            ></el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";

export default {
  components: {
    Pagination,
  },
  data() {
    // 验证手机号的规则
    let checkMobile = (rule, value, cb) => {
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

      if (reg.test(value)) {
        // 合法的手机号
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    // 验证域名的规则
    let checkDomainName = (rule, value, cb) => {
      let reg = /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$/;

      if (reg.test(value)) {
        // 合法的域名
        return cb();
      }
      cb(new Error("请输入合法的域名"));
    };
    // 验证ip的规则
    let checkIP = (rule, value, cb) => {
      let reg = /((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)/;

      if (reg.test(value)) {
        // 合法的ip
        return cb();
      }
      cb(new Error("请输入合法的ip"));
    };
    // 密码安全性要求
    let validatePass = (rule, value, callback) => {
      // 6-16位, 数字, 字母, 字符至少包含两种, 同时不能包含中文和空格
      let reg = /(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{6,16}$/;
      if (!reg.test(value)) {
        callback(new Error("密码长度需6-16位，数字、字母、字符至少包含两种"));
      } else {
        callback();
      }
    };

    return {
      obj: {
        total: 0,
      },
      users: [],
      hideUpload: false,
      showLogo: false,
      uploadData: {},
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      dialogTitle: "添加总代理",
      initialAddForm: {},
      // 添加用户的表单数据
      addForm: {
        id: "",
        phone: "",
        commission: "",
        full_name: "",
        email: "",
        website_name: "",
        domain_name: "",
        ip: "",
        logoList: [],
        logo: "",
        start_time: "",
        end_time: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        commission: [{ required: true, message: "请输入数字", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
        full_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
        ],
        website_name: [{ required: true, message: "请输入网站名称", trigger: "blur" }],
        domain_name: [
          { required: true, message: "请输入网站域名", trigger: "blur" },
          { validator: checkDomainName, trigger: "blur" },
        ],
        ip: [
          { required: true, message: "请输入网站ip", trigger: "blur" },
          { validator: checkIP, trigger: "blur" },
        ],
        start_time: [{ required: true, message: "请选择开始时间", trigger: "change" }],
        end_time: [{ required: true, message: "请选择结束时间", trigger: "change" }],
      },
    };
  },
  created() {
    this.init();
    this.getUserList();
    this.$store.commit("changeBreadcrumb", this.$route);
  },
  methods: {
    uploadSuccess(res, file) {
      this.hideUpload = true;
      this.addForm.logo = this.showImgUrl + res.data;
      console.log(this.addForm.logo, "logo");
    },
    beforeUpload(file) {
      this.uploadData.files = file;
      // console.log(file.size);
      const isLt2M = file.size / 1024 / 1024 < 0.05;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 50KB!");
      } else {
        this.hideUpload = true;
      }
      return isLt2M;
    },
    dateChange(value) {
      console.log(value, "选中的日期");
    },
    handleRemove(file, fileList) {
      setTimeout(() => {
        this.hideUpload = false;
        this.showLogo = false;
      }, 200);
      console.log(file, fileList);
    },
    search() {
      let reg = /\S/g;
      // 若输入内容为空，禁止查询
      if (!reg.test(this.queryInfo.query)) return;
      this.getUserList();
    },
    // 初始化表单
    init() {
      this.initialAddForm = Object.assign({}, this.addForm);
    },
    async getUserList(page) {
      if (page && page.newPage) this.queryInfo.pagenum = page.newPage;
      if (page && page.newSize) this.queryInfo.pagesize = page.newSize;

      const formData = new FormData();
      formData.append("name", this.queryInfo.query);
      formData.append("page", this.queryInfo.pagenum);
      formData.append("rows", this.queryInfo.pagesize);
      formData.append("user_type", 2);
      const { data: res } = await this.$http.post("findByPage", formData);
      console.log(res, "总代理信息");
      if (res.code != "0") return this.$message("获取总代理信息失败");

      res.data.result.forEach((item) => {
        if (item.logo.includes("http")) {
          item.logoList = [];
          item.logoList.push({
            name: Math.random(),
            url: item.logo,
          });
        }
      });
      this.users = res.data.result;
      this.obj.total = res.data.totalCount;
    },
    // 监听 switch 开关状态的改变
    userStateChanged(row) {
      this.$confirm("确定改变用户状态？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let status = row.status == 0 ? 1 : 0;
          const formData = new FormData();
          formData.append("id", row.id);
          formData.append("status", status);
          const { data: res } = await this.$http.post("updateStatus", formData);
          console.log(res, "更新状态返回");
          if (res.code != "0") {
            return this.$message.error("改变用户状态失败！");
          }
          row.status = status;
          this.$message.success("改变用户状态成功");
          // 重新获取用户列表数据
          this.getUserList();
        })
        .catch(() => {
          this.$message("已取消修改！");
        });
    },
    // 对话框关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      this.showLogo = false;
      this.hideUpload = false;
      this.$refs.upload.clearFiles();
      this.dialogTitle = "添加总代理";
      // 对话框关闭后,初始化表单数据
      console.log(this.initialAddForm, "initialAddForm");
      this.addForm = Object.assign({}, this.initialAddForm);
      console.log(this.addForm, "对话框关闭");
    },
    // 编辑用户资料
    edit(row) {
      this.dialogTitle = "编辑总代理";
      this.addDialogVisible = true;
      if (row.logo.includes("http")) this.showLogo = true;
      Object.assign(this.addForm, row);
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const form = this.addForm;
        const formData = new FormData();
        formData.append("user_type", 2);
        formData.append("phone", form.phone);
        formData.append("commission", form.commission);
        formData.append("full_name", form.full_name);
        formData.append("email", form.email);
        formData.append("website_name", form.website_name);
        formData.append("domain_name", form.domain_name);
        formData.append("ip", form.ip);
        formData.append("logo", form.logo);
        formData.append("start_time", form.start_time);
        formData.append("end_time", form.end_time);
        let res;
        if (form.id) {
          formData.append("id", form.id);
          res = await this.$http.post("update", formData);
        } else {
          res = await this.$http.post("save", formData);
        }
        console.log(res.data, "添加或者编辑用户返回的信息");
        if (res.data.code != "0") return this.$message.error("操作失败！");

        this.$message.success("操作成功！");
        // 隐藏添加用户的对话框
        this.addDialogVisible = false;
        // 重新获取用户列表数据
        this.getUserList();
      });
    },
    // 重置用户密码
    resetPwd(row) {
      this.$confirm("确定重置用户密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const formData = new FormData();
          formData.append("name", row.name);
          const { data: res } = await this.$http.post("resetPwd", formData);
          if (res.code != "0") {
            return this.$message.error("重置用户密码失败！");
          }
          this.$message.success("重置用户密码成功");
          // 重新获取用户列表数据
          this.getUserList();
        })
        .catch(() => {
          this.$message("已取消重置！");
        });
    },
    // 根据id删除对应的用户信息
    async removeUserById(row) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm("此操作将永久删除该用户 , 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      //console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message("已取消删除");
      }

      // console.log(row);
      const formData = new FormData();
      // formData.append("id", row);
      formData.append("ids", [row]);
      const { data: res } = await this.$http.post("del", formData);
      console.log(res, "删除返回信息");
      if (res.code != "0") {
        return this.$message.error("删除用户失败！");
      }
      this.$message.success("删除用户成功！");
      this.getUserList();
    },
  },
};
</script>

<style lang="scss">
.agency-wrapper {
  .addForm {
    margin: auto;
    padding-right: 50px;
    .line {
      text-align: center;
    }
    .hide {
      .el-upload--picture-card {
        display: none;
      }
    }
    .showLogo {
      .el-upload--picture-card {
        z-index: -1;
      }
    }
    .avatar-uploader {
      height: 80px;
      .el-upload--picture-card {
        position: absolute;
        top: 0;
        left: 0;
      }
      .el-icon-plus {
        font-size: 20px;
        color: #8c939d;
        width: 250px;
        height: 80px;
        line-height: 80px;
        text-align: center;
      }
    }
    .el-upload-list--picture-card .el-upload-list__item-status-label i {
      position: absolute;
      right: 15px;
      top: 0;
    }
    .avatar-uploader .el-upload-list--picture-card .el-upload-list__item,
    .el-upload--picture-card {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 250px;
      height: 80px;
      line-height: 80px;
      text-align: center;
      .el-icon-close-tip {
        display: none;
      }
    }
  }
}
</style>
